<template>
  <div style="display: flex;height: 800px;overflow:hidden;">
    <br>
    <div style="transition: all .5s;width: 250px;overflow-x: hidden" ref="collapse">
      <div
          style="background-color: #fafbff;border-left: 1px dashed #cccccc;height: 100%;position: relative">
        <div style="overflow: hidden">
          <img @click="collapse" ref="collapseImage"
               style="position: absolute;right: -15px;top: 50%;background-color: white;border-radius: 10px;border: 1px dashed #cccccc;width: 30px;height: 40px"
               src="@/assets/image/arrow-left-s-line.png" alt="">
          <div style="display: flex;justify-content: center;flex-wrap: wrap">
            <el-input @keyup.enter.native="getList" v-model="queryDialogueByTitle" prefix-icon="el-icon-search"
                      placeholder="输入搜索对话"></el-input>
            <el-button @click="getList" class="el-icon-search">搜索</el-button>
            <el-button @click="handleReset" class="el-icon-refresh-right">重置</el-button>
            <el-button @click="createNewDialogue" class="el-icon-plus">新对话</el-button>
          </div>
          <div v-if="Dialogue.length">
            <div class="dialogue-box" v-for="item in Dialogue" :key="item.id">
              <div @click="getChatMessage(item.id)">
                <div style="display: flex;align-items: center;justify-content: space-between">
                  <strong>
                    {{ item.dialogueTitle }}
                  </strong>
                  <div style="padding: 10px;z-index: 9" @click="deleteDialogue($event,item.id,item.dialogueTitle)"
                       class="el-icon-delete"></div>
                </div>
                <br>
                <small>
                  {{ item.createdAt }}
                </small>
              </div>
            </div>
          </div>
          <div v-else>
            <el-empty></el-empty>
          </div>
        </div>
      </div>
    </div>
    <div v-if="dialogVisible" style="margin: 20% auto">
      <div style="">
        <div>
          <h1>中国非物质文化遗产向导</h1>
          <br>
          <div style="text-align: center">
            <img style="width: 100px" src="@/assets/image/组件向导-copy-copy.png" alt="">
          </div>
          <br>
          <div style="text-align: center">
            <el-button @click="createNewDialogue" class="el-icon-plus" type="warning"> 创建新对话</el-button>
          </div>
        </div>
      </div>
    </div>
    <div v-else style="position: relative;width: 100%;margin: 0 50px;">
      <div class="messages" style="height: 90%;overflow-x: hidden;">
        <div v-for="item in ChatMessage" :key="item.id">
          <div
              :class="{'robot-message-super' : item.messageType === 'robot','you-message-super' :  item.messageType === 'user'}">
            <div :class="{'robot-message' : item.messageType === 'robot','you-message' :  item.messageType === 'user'}">
              <img style="width: 30px;height: 30px" v-if="item.messageType === 'robot'" src="@/assets/image/向导.png"
                   alt="">
              <el-image v-else :src="userInfo.imageUrl || avatar"
                        alt="img" style="height: 30px;width: 30px;border-radius: 50%"/>
              <div v-html="item.content"></div>
              <small>{{ item.createdAt }}</small>
            </div>
          </div>
        </div>
      </div>
      <div style="padding: 10px;width: 100%;display: flex;justify-content: center">
        <el-input v-model="title" placeholder="说点什么呢？"></el-input>
        <el-button v-noMoreClick type="primary" @click="send" :disabled="isDisabled">发送(10积分一次)</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import {
  addChatMessage,
  addDialogue,
  deleteDialogue,
  getChatMessage,
  getDialogueById
} from "@/api/request/AIToolRequest";
import {getBeijingTime} from "@/utils/DataTime";

export default {
  name: "ChatView",
  data() {
    return {
      collapseFlag: false,
      userInfo: {},
      Dialogue: [],
      ChatMessage: [],
      dialogVisible: true,
      title: '',
      dialogueId: null,
      isDisabled: false,
      queryDialogueByTitle: null,
      avatar: require('@/assets/image/no_image.png'),
    }
  },
  methods: {
    // 需要区分开新对话和在当前对话发送信息
    createNewDialogue() {
      this.title = ''
      this.dialogVisible = false
      this.ChatMessage = []
      this.dialogueId = null
    },
    send() {
      if (!this.userInfo) {
        this.$message.warning('请先登录');
        return;
      }

      if (!this.title.trim()) {
        this.$message.warning('请先说点什么');
        return;
      }

      // 怎么样才算新对话 有对话id，没有就是新对话
      if (!this.dialogueId) {
        addDialogue(this.title, this.userInfo.id).then(res => {
          if (res.code !== 200) {
            this.$message.error(res.msg);
            return;
          }
          this.getList()
          this.dialogueId = res.data.id
          this.fetchChat()
          this.title = ''
        }).catch(error => {
          console.log(error)
        });
      } else {
        this.fetchChat()
      }
    },
    async fetchChat() {
      this.scrollToBottom()
      this.isDisabled = true
      const userMessage = {
        messageType: 'user',
        content: this.title,
        dialogueId: this.dialogueId,
        createUserId: this.userInfo.id,
        createdAt: getBeijingTime()
      }
      this.ChatMessage.push(userMessage)

      try {
        // 构造机器人回复的信息
        let currentMessage = {
          messageType: 'robot',
          content: '正在思考中...',
          createdAt: getBeijingTime()
        };
        // 推送
        this.ChatMessage.push(currentMessage);

        const {read} = await addChatMessage(userMessage)

        // 调用read方法每次调用时都会从响应体流中读取一块数据，并将其解码为文本返回
        let chunk = await read();
        // done返回true时代表已经读取完毕，false代表还有数据可以读取，取反继续执行
        currentMessage.content = ''
        while (!chunk.done) {
          currentMessage.content += chunk.value;
          // 更新信息数组中最后一个索引的数据
          this.$set(this.ChatMessage, this.ChatMessage.length - 1, currentMessage); // 更新最后一条消息
          this.scrollToBottom();
          // 继续调用read()将读取的结果返回即{done, value: chunk}
          chunk = await read();
        }
      } catch (error) {
        this.ChatMessage.push({messageType: 'error', content: 'Error: ' + error.message, createdAt: new Date()});
      } finally {
        // 清空输入框
        this.title = '';
        this.isDisabled = false
        this.scrollToBottom();
      }
    },
    // 将容器滚动到底部
    scrollToBottom() {
      // 使用 this.$nextTick 确保 DOM 已更新。
      this.$nextTick(() => {
        // 获取包含类名为 .messages 的元素
        const container = this.$el.querySelector('.messages');
        // 设置该元素的 scrollTop 属性为 scrollHeight，使其滚动到底部。
        container.scrollTop = container.scrollHeight;
      });
    },
    collapse() {
      if (!this.collapseFlag) {
        this.$refs.collapse.style.width = '3%'
        this.$refs.collapseImage.style.transform = 'rotate(180deg)'
      } else {
        this.$refs.collapse.style.width = '18.5%'
        this.$refs.collapseImage.style.transform = 'rotate(0deg)'
      }

      this.collapseFlag = !this.collapseFlag
    },
    deleteDialogue(event, dialogueId, dialogueTitle) {
      event.stopPropagation();

      this.$confirm(`删除对话为：${dialogueTitle}`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteDialogue(dialogueId).then(res => {
          if (res.code !== 200) {
            this.$message.error(res.msg);
            return;
          }

          this.getList()
        }).catch(error => {
          console.log(error)
        });
      }).catch(() => {
      });

    },
    getList() {
      if (!this.userInfo) {
        return
      }

      this.queryDialogueByTitle = null
      getDialogueById(this.userInfo.id, this.queryDialogueByTitle).then(res => {
        if (res.code !== 200) {
          this.$message.error(res.msg);
          return;
        }

        this.title = ''
        this.Dialogue = res.data;
      }).catch(error => {
        console.log(error)
      });
    },
    getChatMessage(dialogueId) {
      this.dialogueId = dialogueId
      getChatMessage(dialogueId).then(res => {
        if (res.code !== 200) {
          this.$message.error(res.msg);
          return;
        }

        this.title = ''
        this.dialogVisible = false
        this.ChatMessage = res.data;
        this.scrollToBottom()

      }).catch(error => {
        console.log(error)
      });
    },
    handleReset() {
      this.queryDialogueByTitle = null
      this.getList()
    }
  },
  mounted() {
    this.userInfo = JSON.parse(localStorage.getItem('xm-user'))
    this.getList()
    this.$notify({
      title: '使用提示',
      message: '<p>新用户赠送<strong>1000积分</strong>，可调用<strong>100次</strong>。<em>使用完后需点击用户头像进入个人中心充值界面购买积分</em>。</p>',
      duration: 0,
      offset: 100,
      dangerouslyUseHTMLString: true
    });
  }
}
</script>

<style>
.el-scrollbar__wrap {
  overflow-x: auto;
  overflow: inherit;
}
</style>
<style scoped lang="scss">
.dialogue-box {
  background-color: #f4f2ff;
  padding: 10px;
  margin: 10px;
  border-radius: 10px;
  transition: all .5s;
  cursor: pointer;
}

.dialogue-box:hover {
  background-color: #e6e0fd;
}

.robot-message-super {
  display: flex;
  justify-content: left;
}

.robot-message {
  background-color: #f4f4f4;
  padding: 20px;
  border-radius: 10px;
  display: inline-block;
  margin: 10px 0;
}

.you-message-super {
  display: flex;
  justify-content: right;
}

.you-message {
  background-color: #e1deff;
  padding: 20px;
  border-radius: 10px;
  display: inline-block;
  margin: 10px 0;
}
</style>
